﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace WWF.Data
{
    public class DBconnection
    {
        public static void UpdateDbConn(string path, ref Configuration config)
        {
            bool isModified = false;

            path = path.Remove(path.LastIndexOf(".")) + ".Data";
            string uniApplicationStr = @"metadata=res://*/UniversityApplicationModel.csdl|res://*/UniversityApplicationModel.ssdl|res://*/UniversityApplicationModel.msl;provider=System.Data.SqlClient;provider connection string=""data source=.\SQLEXPRESS;attachdbfilename="
                    + path + @"\UniversityApplication.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework""";

            var uniApplicationConn = config.ConnectionStrings.ConnectionStrings["UniversityApplicationEntities"];

            if (null != uniApplicationConn
                && !uniApplicationConn.ToString().Equals(uniApplicationStr))
            {
                uniApplicationConn.ConnectionString = uniApplicationStr;
                isModified = true;
            }

            path = path.Remove(path.LastIndexOf(".")) + ".Services";
            string wfPersistenceStr = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename="
                    + path + @"\App_Data\WFPersistence.mdf;User Instance=true";

            var wfPersistenceConn = config.ConnectionStrings.ConnectionStrings["WFPersistence"];

            if (null != wfPersistenceConn
                && !wfPersistenceConn.ToString().Equals(wfPersistenceStr))
            {
                wfPersistenceConn.ConnectionString = wfPersistenceStr;
                isModified = true;
            }

            if (isModified)
            {
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("ConnectionStrings");
            }
        }
    }
}
